import 'package:cbec_app/components/base/base_nav_bar.dart';
import 'package:cbec_app/utils/ImageHelper.dart';
import 'package:cbec_app/utils/ThemeConfig.dart';
import 'package:cbec_app/utils/Tools.dart';
import 'package:cbec_app/utils/logger.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class BasePage extends StatefulWidget {
  ///导航栏标题
  final String? title;

  ///是否为图标+标题
  final bool? isIconTitle;

  ///是否为搜索框
  final bool? isSearch;

  ///是否显示分享按钮
  final bool? isShowShare;

  /// 分享按钮回调
  final VoidCallback? shareCallBack;

  ///当点击输入框时需要跳转的路由名称(不传则不跳转)
  final String routeName;

  ///是否显示菜单图标
  final bool isShowMenuIcon;

  ///标题颜色
  final Color? titleColor;

  ///标题大小
  final double titleSize;

  ///页面背景图片url(根据传入的url自动使用本地或网络图片，设置了背景图，背景颜色属性将不再生效)
  final String? bgImageUrl;

  ///背景图适配方式
  final BoxFit bgImgFit;

  ///页面背景颜色(需将bgType设置为pureColor)
  final Color? bgColor;

  ///页面背景渐变色(需将bgType设置为gradientColor)
  final Gradient? gradient;

  ///左侧图标类型
  final IconType? iconType;

  ///搜索框样式类型
  final SearchStyleType? searchType;

  ///输入框是否自动聚焦
  final bool isAutoFocus;

  ///导航背景色
  final Color? navBgColor;

  ///是否显示导航底部边框
  final bool isShowNavBottomBorder;

  ///body背景色
  final Color? bodyColor;

  ///body顶部间距
  final double? paddingTop;

  ///body底部间距
  final double? paddingBottom;

  ///是否显示边距
  final bool? isShowPadding;

  ///是否禁止滚动
  final bool? isDisableScroll;

  ///搜索框placeholder
  final String placeholder;

  ///tabbar高度
  final double tabHeight;

  ///tabbar子节点列表(固定定位，不随页面滚动)
  final List<Widget>? tabChildren;

  ///tabbar背景色
  final Color tabBgColor;

  ///搜索框事件监听
  final void Function(String)? onInput;

  ///子组件列表
  final List<Widget>? children;

  ///装修相关
  ///导航栏类型(将使用后台配置的参数渲染)
  final NavType navType;

  ///自定义导航栏组件
  final Widget? customWidget;

  ///装修导航配置
  final Map<String, dynamic>? decorationInfo;

  ///刷新控制器(不传时默认关闭下拉刷新)
  final RefreshController? refreshController;

  ///监听页面下拉刷新
  final VoidCallback? onPageRefresh;

  ///监听页面上拉加载
  final VoidCallback? onPageLoading;

  ///是否启用下拉刷新
  final bool? enablePullDown;

  ///是否启用上拉加载
  final bool enablePullUp;

  ///是否为沉浸式导航
  final bool isImmersionNav;

  ///输入框是否禁用
  final bool isDisable;

  ///原生body容器
  final Widget? bodyWidget;

  ///页面滑动回调
  ///向下滑动
  final Function()? onScrollDown;

  ///向上滑动到顶部
  final Function()? onScrollTop;

  ///阻止默认返回事件
  final VoidCallback? beforeBack;

  ///点击搜索按钮进行搜索
  final Function(String value)? onClickSearch;

  ///搜索框控制器
  final TextEditingController? textEditingController;

  ///页面基础布局
  BasePage(
      {super.key,
      this.children,
      this.title = '',
      this.isIconTitle = false,
      this.titleSize = 16,
      this.titleColor = Colors.black,
      this.isSearch = false,
      this.isShowShare = false,
      this.shareCallBack,
      this.bgImageUrl,
      this.bgImgFit = BoxFit.fill,
      this.bgColor = Colors.white,
      this.iconType = IconType.none,
      this.searchType = SearchStyleType.none,
      this.navBgColor = Colors.transparent,
      this.bodyColor,
      this.isDisableScroll = false,
      this.paddingTop = 0,
      this.paddingBottom = 0,
      this.isShowPadding = false,
      this.placeholder = '搜索商品',
      this.tabHeight = 0,
      this.tabChildren,
      this.tabBgColor = Colors.transparent,
      this.onInput,
      this.routeName = '',
      this.isShowNavBottomBorder = false,
      this.isAutoFocus = false,
      this.gradient,
      this.navType = NavType.common,
      this.customWidget,
      this.decorationInfo,
      this.refreshController,
      this.onPageRefresh,
      this.onPageLoading,
      this.enablePullDown,
      this.enablePullUp = false,
      this.isShowMenuIcon = false,
      this.isImmersionNav = false,
      this.isDisable = true,
      this.onScrollDown,
      this.onScrollTop,
      this.beforeBack,
      this.onClickSearch,
      this.textEditingController,
      this.bodyWidget});

  @override
  State<StatefulWidget> createState() => _BasePageState();
}

class _BasePageState extends State<BasePage> {
  //边距
  var padding = ThemeConfig.bodyPadding / 2;
  // 内部刷新控制器
  RefreshController _refreshController = RefreshController(initialRefresh: false);
  bool _enablePullDown = false;

  @override
  void initState() {
    super.initState();
    if (widget.refreshController != null) {
      _refreshController = widget.refreshController!;
      _enablePullDown = true;
    } else {
      _enablePullDown = false;
    }
    if (widget.enablePullDown != null) {
      _enablePullDown = widget.enablePullDown!;
    }
  }

  //监听下拉刷新
  void _onRefresh() async {
    if (widget.onPageRefresh != null) {
      widget.onPageRefresh!();
    }
  }

  ///加载
  void _onLoading() async {
    if (widget.onPageLoading != null) {
      widget.onPageLoading!();
    }
  }

  @override
  Widget build(BuildContext context) {
    return NotificationListener(
        onNotification: (notification) {
          if (notification is UserScrollNotification) {
            //向下
            final double currentPixel = notification.metrics.pixels;
            if (currentPixel > 0) {
              if (widget.onScrollDown != null) {
                widget.onScrollDown!();
              }
            } else {
              if (widget.onScrollTop != null) {
                widget.onScrollTop!();
              }
            }
          }
          return false;
        },
        child: widget.bodyWidget == null ? _getBgBox() : useBodyWidget());
  }

  ///body子组件列表
  List<Widget> _getChildren(List<Widget> list) {
    List<Widget> renderArr = []; //待渲染组件列表
    List<Widget> normalArr = []; //常规组件列表
    for (int i = 0; i < list.length; i++) {
      var name = list[i].toString();
      var key = list[i].key.toString();
      //定位组件
      if (name.contains('Positioned') || key.contains('Positioned')) {
        renderArr.add(list[i]);
      } else {
        //常规组件
        normalArr.add(list[i]);
      }
    }
    renderArr.insert(0, _bodyWidget(normalArr));

    // //添加底部间距
    // arr.add(SizedBox(
    //   width: double.infinity,
    //   height: widget.pageBottom,
    // ));
    // logger.d('渲染的组件列表 $renderArr');
    return renderArr;
  }

  ///body容器
  Widget _bodyWidget(List<Widget> list) {
    return Container(
        color: widget.bodyColor ?? ThemeConfig.bodyColor,
        padding: widget.isShowPadding! ? EdgeInsets.only(left: padding.w, right: padding.w, top: widget.paddingTop ?? 0, bottom: widget.paddingBottom ?? 0) : const EdgeInsets.all(0),
        child: pullRefresh(ListView(
          physics: widget.isDisableScroll! ? const NeverScrollableScrollPhysics() : const AlwaysScrollableScrollPhysics(),
          children: list,
        )));
  }

  ///获取背景容器
  Widget _getBgBox() {
    if (widget.isImmersionNav) {
      return Container(
          decoration: BoxDecoration(
            color: widget.bgColor,
            gradient: widget.gradient,
          ),
          child: Scaffold(
            body: Stack(children: _getChildren(widget.children ?? [])),
          ));
    } else {
      if (widget.bgImageUrl != null) {
        return Container(
            decoration: BoxDecoration(
              color: widget.bgColor,
              gradient: widget.gradient,
              image: DecorationImage(image: ImageHelper.imgProvider(widget.bgImageUrl!), fit: widget.bgImgFit, repeat: ImageRepeat.repeatY, alignment: Alignment.topCenter),
            ),
            child: Scaffold(
              appBar: _topNavConfig(),
              backgroundColor: Colors.transparent,
              body: Stack(children: _getChildren(widget.children ?? [])),
            ));
      } else {
        return Container(
            decoration: BoxDecoration(
              color: widget.bgColor,
              gradient: widget.gradient,
            ),
            child: Scaffold(
              appBar: _topNavConfig(),
              backgroundColor: Colors.transparent,
              body: Stack(children: _getChildren(widget.children ?? [])),
            ));
      }
    }
  }

  ///使用原始body容器
  Widget useBodyWidget() {
    return Container(
        decoration: BoxDecoration(
          color: widget.bgColor,
          gradient: widget.gradient,
        ),
        child: Scaffold(
          appBar: _topNavConfig(),
          backgroundColor: Colors.transparent,
          body: widget.bodyWidget,
        ));
  }

  ///下拉刷新组件
  Widget pullRefresh(Widget child) {
    return Tools.getPullRefresh(refreshController: _refreshController, enablePullDown: _enablePullDown, enablePullUp: widget.enablePullUp, onRefresh: _onRefresh, onLoading: _onLoading, child: child);
  }

  ///顶部导航栏配置
  PreferredSizeWidget _topNavConfig() {
    return BaseNavBar(
      navHeight: 44,
      title: widget.title!,
      titleSize: widget.titleSize,
      iconType: widget.iconType!,
      isIconTitle: widget.isIconTitle!,
      color: widget.titleColor!,
      isSearch: widget.isSearch!,
      isShowShare: widget.isShowShare!,
      shareCallBack: widget.shareCallBack,
      navBgColor: widget.navBgColor!,
      searchType: widget.searchType!,
      placeholder: widget.placeholder,
      tabHeight: widget.tabHeight,
      tabBgColor: widget.tabBgColor,
      tabChildren: widget.tabChildren,
      onInput: widget.onInput,
      routeName: widget.routeName,
      isShowNavBottomBorder: widget.isShowNavBottomBorder,
      isAutoFocus: widget.isAutoFocus,
      navType: widget.navType,
      customWidget: widget.customWidget,
      info: widget.decorationInfo,
      isShowMenuIcon: widget.isShowMenuIcon,
      isDisable: widget.isDisable,
      beforeBack: widget.beforeBack,
      onClickSearch: widget.onClickSearch,
      textEditingController: widget.textEditingController,
    );
  }
}
